import { reqLogin, reqLogout } from '@/api'

const state = {
  userInfo: {
    name: localStorage.getItem('userName'),
    token: localStorage.getItem('token'),
  },
}

const actions = {
  // 登录
  async userLogin({ commit }, userObj) {
    const res = await reqLogin(userObj)
    if (res.code === 200) {
      commit('SAVE_USER_INFO', res.data)
      localStorage.setItem('userName', res.data.name)
      localStorage.setItem('token', res.data.token)
    }
    return res
  },
  // 登出
  async userLogout({ commit }) {
    const res = await reqLogout()
    if (res.code === 200) {
      localStorage.removeItem('userName')
      localStorage.removeItem('token')
      commit('REMOVE_USERINFO')
    } else {
      console.log(res.message)
    }
  },
}

const mutations = {
  SAVE_USER_INFO(state, payload) {
    state.userInfo.name = payload.name
    state.userInfo.token = payload.token
  },
  REMOVE_USERINFO(state) {
    state.userInfo.name = ''
    state.userInfo.token = ''
  },
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
}
